package com.tuoyu.replace.tool;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;

/**
 * 项目架构改造工具
 * 将单体应用按照微服务架构进行改造
 * 
 * @author tuoyu
 */
public class ProjectRefactorTool {
    
    // 源项目路径
    private static final String SOURCE_PROJECT = "D:\\project\\gimiii\\v2\\interface-platform";
    
    // 目标项目根路径
    private static final String TARGET_BASE_PATH = "D:\\project\\gimiii\\v2\\interface-platform-refactored";
    
    // 项目名称前缀
    private static final String PROJECT_PREFIX = "interface";
    
    /**
     * 模块分类规则
     */
    private static class ModuleClassifier {
        // API模块（对外暴露的接口定义）
        static final List<String> API_PATTERNS = Arrays.asList(
            "dto", "domain", "document"
        );
        
        // 公共核心模块
        static final List<String> COMMON_CORE_PATTERNS = Arrays.asList(
            "common/BaseDto", "common/Constant", "common/ErrorCodeEnum",
            "common/PageDto", "common/AppEnum", "common/MapUtil"
        );
        
        // 公共工具模块
        static final List<String> COMMON_UTIL_PATTERNS = Arrays.asList(
            "util", "common/util", "common/shanheutil"
        );
        
        // 日志模块
        static final List<String> COMMON_LOG_PATTERNS = Arrays.asList(
            "config/InterfaceUseInfoInterceptor"
        );
        
        // MyBatis/数据库模块
        static final List<String> COMMON_MYBATIS_PATTERNS = Arrays.asList(
            "jpa"
        );
        
        // Redis模块
        static final List<String> COMMON_REDIS_PATTERNS = Arrays.asList(
            "config/IdGeneratorConfig", "config/LongIdGeneratorConfig"
        );
        
        // 安全模块
        static final List<String> COMMON_SECURITY_PATTERNS = Arrays.asList(
            "config/ApiCheck", "config/Secret", "config/Appid"
        );
        
        // OSS对象存储模块
        static final List<String> COMMON_OSS_PATTERNS = Arrays.asList(
            "config/ali/AliFaceConfiguration", "config/ali/AliOcrConfiguration"
        );
        
        // 业务模块（controller、service）
        static final List<String> BUSINESS_MODULE_PATTERNS = Arrays.asList(
            "controller", "service", "component"
        );
        
        // 配置模块
        static final List<String> CONFIG_PATTERNS = Arrays.asList(
            "config"
        );
    }
    
    /**
     * 目标模块结构
     */
    private enum TargetModule {
        // API模块
        API_SYSTEM(PROJECT_PREFIX + "-api/" + PROJECT_PREFIX + "-api-system/src/main/java"),
        
        // 公共模块
        COMMON_CORE(PROJECT_PREFIX + "-common/" + PROJECT_PREFIX + "-common-core/src/main/java"),
        COMMON_LOG(PROJECT_PREFIX + "-common/" + PROJECT_PREFIX + "-common-log/src/main/java"),
        COMMON_MYBATIS(PROJECT_PREFIX + "-common/" + PROJECT_PREFIX + "-common-mybatis/src/main/java"),
        COMMON_REDIS(PROJECT_PREFIX + "-common/" + PROJECT_PREFIX + "-common-redis/src/main/java"),
        COMMON_SECURITY(PROJECT_PREFIX + "-common/" + PROJECT_PREFIX + "-common-security/src/main/java"),
        COMMON_OSS(PROJECT_PREFIX + "-common/" + PROJECT_PREFIX + "-common-oss/src/main/java"),
        
        // 业务模块
        MODULES_SYSTEM(PROJECT_PREFIX + "-modules/" + PROJECT_PREFIX + "-system/src/main/java"),
        
        // 网关
        GATEWAY(PROJECT_PREFIX + "-gateway/src/main/java"),
        
        // 认证服务
        AUTH(PROJECT_PREFIX + "-auth/src/main/java");
        
        private final String path;
        
        TargetModule(String path) {
            this.path = path;
        }
        
        public String getPath() {
            return path;
        }
    }
    
    /**
     * 执行改造
     */
    public void refactor() throws IOException {
        System.out.println("==== 开始项目架构改造 ====");
        System.out.println("源项目: " + SOURCE_PROJECT);
        System.out.println("目标路径: " + TARGET_BASE_PATH);
        
        // 1. 创建目标目录结构
        createTargetStructure();
        
        // 2. 分析源项目结构
        Map<String, List<File>> classifiedFiles = analyzeSourceProject();
        
        // 3. 复制文件到对应模块
        copyFilesToTargetModules(classifiedFiles);
        
        // 4. 创建各模块的pom.xml
        createPomFiles();
        
        // 5. 创建配置文件
        createConfigFiles();
        
        // 6. 生成迁移报告
        generateReport(classifiedFiles);
        
        System.out.println("==== 架构改造完成 ====");
    }
    
    /**
     * 创建目标目录结构
     */
    private void createTargetStructure() throws IOException {
        System.out.println("\n>>> 创建目标目录结构...");
        
        for (TargetModule module : TargetModule.values()) {
            Path modulePath = Paths.get(TARGET_BASE_PATH, module.getPath());
            Files.createDirectories(modulePath);
            
            // 创建resources目录
            Path resourcesPath = Paths.get(modulePath.toString().replace("java", "resources"));
            Files.createDirectories(resourcesPath);
            
            System.out.println("  创建: " + module.name());
        }
    }
    
    /**
     * 分析源项目结构
     */
    private Map<String, List<File>> analyzeSourceProject() throws IOException {
        System.out.println("\n>>> 分析源项目结构...");
        
        Map<String, List<File>> classifiedFiles = new HashMap<>();
        Path sourcePath = Paths.get(SOURCE_PROJECT, "src/main/java");
        
        if (!Files.exists(sourcePath)) {
            throw new IOException("源项目路径不存在: " + sourcePath);
        }
        
        Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                if (file.toString().endsWith(".java")) {
                    String relativePath = sourcePath.relativize(file).toString();
                    String moduleType = classifyFile(relativePath);
                    
                    classifiedFiles.computeIfAbsent(moduleType, k -> new ArrayList<>())
                        .add(file.toFile());
                }
                return FileVisitResult.CONTINUE;
            }
        });
        
        // 输出分类统计
        classifiedFiles.forEach((module, files) -> {
            System.out.println("  " + module + ": " + files.size() + " 个文件");
        });
        
        return classifiedFiles;
    }
    
    /**
     * 分类文件
     */
    private String classifyFile(String relativePath) {
        String normalizedPath = relativePath.replace("\\", "/");
        
        // API模块判断（DTO、Domain、Document等）
        if (ModuleClassifier.API_PATTERNS.stream()
                .anyMatch(pattern -> normalizedPath.contains("/" + pattern + "/"))) {
            return "API_SYSTEM";
        }
        
        // 公共模块判断
        if (ModuleClassifier.COMMON_CORE_PATTERNS.stream()
                .anyMatch(normalizedPath::contains)) {
            return "COMMON_CORE";
        }
        
        if (ModuleClassifier.COMMON_UTIL_PATTERNS.stream()
                .anyMatch(pattern -> normalizedPath.contains("/" + pattern + "/"))) {
            return "COMMON_CORE";  // 工具类也放到core模块
        }
        
        if (ModuleClassifier.COMMON_LOG_PATTERNS.stream()
                .anyMatch(normalizedPath::contains)) {
            return "COMMON_LOG";
        }
        
        if (ModuleClassifier.COMMON_MYBATIS_PATTERNS.stream()
                .anyMatch(pattern -> normalizedPath.contains("/" + pattern + "/"))) {
            return "COMMON_MYBATIS";
        }
        
        if (ModuleClassifier.COMMON_REDIS_PATTERNS.stream()
                .anyMatch(normalizedPath::contains)) {
            return "COMMON_REDIS";
        }
        
        if (ModuleClassifier.COMMON_SECURITY_PATTERNS.stream()
                .anyMatch(normalizedPath::contains)) {
            return "COMMON_SECURITY";
        }
        
        if (ModuleClassifier.COMMON_OSS_PATTERNS.stream()
                .anyMatch(normalizedPath::contains)) {
            return "COMMON_OSS";
        }
        
        // 业务模块判断（Controller、Service等）
        if (ModuleClassifier.BUSINESS_MODULE_PATTERNS.stream()
                .anyMatch(pattern -> normalizedPath.contains("/" + pattern + "/"))) {
            return "MODULES_SYSTEM";
        }
        
        // 配置类
        if (ModuleClassifier.CONFIG_PATTERNS.stream()
                .anyMatch(pattern -> normalizedPath.contains("/" + pattern + "/"))) {
            return "MODULES_SYSTEM";  // 配置类放到业务模块
        }
        
        // 默认放到业务模块
        return "MODULES_SYSTEM";
    }
    
    /**
     * 复制文件到目标模块
     */
    private void copyFilesToTargetModules(Map<String, List<File>> classifiedFiles) throws IOException {
        System.out.println("\n>>> 复制文件到目标模块...");
        
        Path sourcePath = Paths.get(SOURCE_PROJECT, "src/main/java");
        
        for (Map.Entry<String, List<File>> entry : classifiedFiles.entrySet()) {
            String moduleType = entry.getKey();
            List<File> files = entry.getValue();
            
            TargetModule targetModule = TargetModule.valueOf(moduleType);
            Path targetModulePath = Paths.get(TARGET_BASE_PATH, targetModule.getPath());
            
            System.out.println("  复制到 " + moduleType + " ...");
            
            for (File file : files) {
                Path sourceFile = file.toPath();
                Path relativePath = sourcePath.relativize(sourceFile);
                Path targetFile = targetModulePath.resolve(relativePath);
                
                // 创建目标目录
                Files.createDirectories(targetFile.getParent());
                
                // 复制文件
                Files.copy(sourceFile, targetFile, StandardCopyOption.REPLACE_EXISTING);
            }
            
            System.out.println("    完成: " + files.size() + " 个文件");
        }
        
        // 复制资源文件
        copyResourceFiles();
    }
    
    /**
     * 复制资源文件
     */
    private void copyResourceFiles() throws IOException {
        System.out.println("\n>>> 复制资源文件...");
        
        Path sourceResourcePath = Paths.get(SOURCE_PROJECT, "src/main/resources");
        
        if (!Files.exists(sourceResourcePath)) {
            System.out.println("  资源文件夹不存在，跳过");
            return;
        }
        
        // 将资源文件复制到业务模块
        Path targetResourcePath = Paths.get(TARGET_BASE_PATH, 
            TargetModule.MODULES_SYSTEM.getPath().replace("java", "resources"));
        
        copyDirectory(sourceResourcePath, targetResourcePath);
        
        System.out.println("  资源文件复制完成");
    }
    
    /**
     * 递归复制目录
     */
    private void copyDirectory(Path source, Path target) throws IOException {
        Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                Path targetDir = target.resolve(source.relativize(dir));
                Files.createDirectories(targetDir);
                return FileVisitResult.CONTINUE;
            }
            
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Path targetFile = target.resolve(source.relativize(file));
                Files.copy(file, targetFile, StandardCopyOption.REPLACE_EXISTING);
                return FileVisitResult.CONTINUE;
            }
        });
    }
    
    /**
     * 创建POM文件
     */
    private void createPomFiles() throws IOException {
        System.out.println("\n>>> 创建POM文件...");
        
        // 创建父POM
        createParentPom();
        
        // 创建API模块POM
        createApiModulePom();
        
        // 创建Common模块POM
        createCommonModulePom();
        
        // 创建业务模块POM
        createBusinessModulePom();
        
        // 创建网关POM
        createGatewayPom();
        
        // 创建认证服务POM
        createAuthPom();
        
        System.out.println("  POM文件创建完成");
    }
    
    /**
     * 创建父POM
     */
    private void createParentPom() throws IOException {
        String pomContent = """
            <?xml version="1.0" encoding="UTF-8"?>
            <project xmlns="http://maven.apache.org/POM/4.0.0"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                     http://maven.apache.org/xsd/maven-4.0.0.xsd">
                <modelVersion>4.0.0</modelVersion>
                
                <groupId>com.yaoyi</groupId>
                <artifactId>interface-platform</artifactId>
                <version>1.0.0</version>
                <packaging>pom</packaging>
                
                <name>interface-platform</name>
                <description>接口平台微服务架构</description>
                
                <modules>
                    <module>interface-api</module>
                    <module>interface-common</module>
                    <module>interface-modules</module>
                    <module>interface-gateway</module>
                    <module>interface-auth</module>
                </modules>
                
                <properties>
                    <java.version>21</java.version>
                    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
                    <spring-boot.version>3.5.7</spring-boot.version>
                    <spring-cloud.version>2023.0.0</spring-cloud.version>
                    <spring-cloud-alibaba.version>2022.0.0.0</spring-cloud-alibaba.version>
                </properties>
                
                <dependencyManagement>
                    <dependencies>
                        <!-- Spring Boot -->
                        <dependency>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-dependencies</artifactId>
                            <version>${spring-boot.version}</version>
                            <type>pom</type>
                            <scope>import</scope>
                        </dependency>
                        
                        <!-- Spring Cloud -->
                        <dependency>
                            <groupId>org.springframework.cloud</groupId>
                            <artifactId>spring-cloud-dependencies</artifactId>
                            <version>${spring-cloud.version}</version>
                            <type>pom</type>
                            <scope>import</scope>
                        </dependency>
                        
                        <!-- Spring Cloud Alibaba -->
                        <dependency>
                            <groupId>com.alibaba.cloud</groupId>
                            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                            <version>${spring-cloud-alibaba.version}</version>
                            <type>pom</type>
                            <scope>import</scope>
                        </dependency>
                    </dependencies>
                </dependencyManagement>
                
                <build>
                    <plugins>
                        <plugin>
                            <groupId>org.apache.maven.plugins</groupId>
                            <artifactId>maven-compiler-plugin</artifactId>
                            <version>3.11.0</version>
                            <configuration>
                                <source>${java.version}</source>
                                <target>${java.version}</target>
                                <encoding>${project.build.sourceEncoding}</encoding>
                            </configuration>
                        </plugin>
                    </plugins>
                </build>
            </project>
            """;
        
        Path pomPath = Paths.get(TARGET_BASE_PATH, "pom.xml");
        Files.writeString(pomPath, pomContent);
    }
    
    /**
     * 创建API模块POM
     */
    private void createApiModulePom() throws IOException {
        // API父模块POM
        String apiParentPom = """
            <?xml version="1.0" encoding="UTF-8"?>
            <project xmlns="http://maven.apache.org/POM/4.0.0"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                     http://maven.apache.org/xsd/maven-4.0.0.xsd">
                <modelVersion>4.0.0</modelVersion>
                <parent>
                    <groupId>com.yaoyi</groupId>
                    <artifactId>interface-platform</artifactId>
                    <version>1.0.0</version>
                </parent>
                
                <artifactId>interface-api</artifactId>
                <packaging>pom</packaging>
                
                <modules>
                    <module>interface-api-system</module>
                </modules>
            </project>
            """;
        
        Path apiPomPath = Paths.get(TARGET_BASE_PATH, "interface-api/pom.xml");
        Files.createDirectories(apiPomPath.getParent());
        Files.writeString(apiPomPath, apiParentPom);
        
        // API System模块POM
        String apiSystemPom = """
            <?xml version="1.0" encoding="UTF-8"?>
            <project xmlns="http://maven.apache.org/POM/4.0.0"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                     http://maven.apache.org/xsd/maven-4.0.0.xsd">
                <modelVersion>4.0.0</modelVersion>
                <parent>
                    <groupId>com.yaoyi</groupId>
                    <artifactId>interface-api</artifactId>
                    <version>1.0.0</version>
                </parent>
                
                <artifactId>interface-api-system</artifactId>
                
                <dependencies>
                    <dependency>
                        <groupId>com.yaoyi</groupId>
                        <artifactId>interface-common-core</artifactId>
                        <version>${project.version}</version>
                    </dependency>
                </dependencies>
            </project>
            """;
        
        Path apiSystemPomPath = Paths.get(TARGET_BASE_PATH, 
            "interface-api/interface-api-system/pom.xml");
        Files.createDirectories(apiSystemPomPath.getParent());
        Files.writeString(apiSystemPomPath, apiSystemPom);
    }
    
    /**
     * 创建Common模块POM
     */
    private void createCommonModulePom() throws IOException {
        // Common父模块POM
        String commonParentPom = """
            <?xml version="1.0" encoding="UTF-8"?>
            <project xmlns="http://maven.apache.org/POM/4.0.0"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                     http://maven.apache.org/xsd/maven-4.0.0.xsd">
                <modelVersion>4.0.0</modelVersion>
                <parent>
                    <groupId>com.yaoyi</groupId>
                    <artifactId>interface-platform</artifactId>
                    <version>1.0.0</version>
                </parent>
                
                <artifactId>interface-common</artifactId>
                <packaging>pom</packaging>
                
                <modules>
                    <module>interface-common-core</module>
                    <module>interface-common-log</module>
                    <module>interface-common-mybatis</module>
                    <module>interface-common-redis</module>
                    <module>interface-common-security</module>
                    <module>interface-common-oss</module>
                </modules>
            </project>
            """;
        
        Path commonPomPath = Paths.get(TARGET_BASE_PATH, "interface-common/pom.xml");
        Files.createDirectories(commonPomPath.getParent());
        Files.writeString(commonPomPath, commonParentPom);
        
        // 创建各个子模块的POM
        createCommonSubModulePom("core");
        createCommonSubModulePom("log");
        createCommonSubModulePom("mybatis");
        createCommonSubModulePom("redis");
        createCommonSubModulePom("security");
        createCommonSubModulePom("oss");
    }
    
    /**
     * 创建Common子模块POM
     */
    private void createCommonSubModulePom(String moduleName) throws IOException {
        String pomContent = String.format("""
            <?xml version="1.0" encoding="UTF-8"?>
            <project xmlns="http://maven.apache.org/POM/4.0.0"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                     http://maven.apache.org/xsd/maven-4.0.0.xsd">
                <modelVersion>4.0.0</modelVersion>
                <parent>
                    <groupId>com.yaoyi</groupId>
                    <artifactId>interface-common</artifactId>
                    <version>1.0.0</version>
                </parent>
                
                <artifactId>interface-common-%s</artifactId>
                
                <dependencies>
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter</artifactId>
                    </dependency>
                </dependencies>
            </project>
            """, moduleName);
        
        Path pomPath = Paths.get(TARGET_BASE_PATH, 
            String.format("interface-common/interface-common-%s/pom.xml", moduleName));
        Files.createDirectories(pomPath.getParent());
        Files.writeString(pomPath, pomContent);
    }
    
    /**
     * 创建业务模块POM
     */
    private void createBusinessModulePom() throws IOException {
        // Modules父模块POM
        String modulesParentPom = """
            <?xml version="1.0" encoding="UTF-8"?>
            <project xmlns="http://maven.apache.org/POM/4.0.0"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                     http://maven.apache.org/xsd/maven-4.0.0.xsd">
                <modelVersion>4.0.0</modelVersion>
                <parent>
                    <groupId>com.yaoyi</groupId>
                    <artifactId>interface-platform</artifactId>
                    <version>1.0.0</version>
                </parent>
                
                <artifactId>interface-modules</artifactId>
                <packaging>pom</packaging>
                
                <modules>
                    <module>interface-system</module>
                </modules>
            </project>
            """;
        
        Path modulesPomPath = Paths.get(TARGET_BASE_PATH, "interface-modules/pom.xml");
        Files.createDirectories(modulesPomPath.getParent());
        Files.writeString(modulesPomPath, modulesParentPom);
        
        // System模块POM
        String systemPom = """
            <?xml version="1.0" encoding="UTF-8"?>
            <project xmlns="http://maven.apache.org/POM/4.0.0"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                     http://maven.apache.org/xsd/maven-4.0.0.xsd">
                <modelVersion>4.0.0</modelVersion>
                <parent>
                    <groupId>com.yaoyi</groupId>
                    <artifactId>interface-modules</artifactId>
                    <version>1.0.0</version>
                </parent>
                
                <artifactId>interface-system</artifactId>
                
                <dependencies>
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-web</artifactId>
                    </dependency>
                    
                    <dependency>
                        <groupId>com.yaoyi</groupId>
                        <artifactId>interface-api-system</artifactId>
                        <version>${project.version}</version>
                    </dependency>
                    
                    <dependency>
                        <groupId>com.yaoyi</groupId>
                        <artifactId>interface-common-core</artifactId>
                        <version>${project.version}</version>
                    </dependency>
                    
                    <dependency>
                        <groupId>com.yaoyi</groupId>
                        <artifactId>interface-common-mybatis</artifactId>
                        <version>${project.version}</version>
                    </dependency>
                </dependencies>
                
                <build>
                    <plugins>
                        <plugin>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-maven-plugin</artifactId>
                        </plugin>
                    </plugins>
                </build>
            </project>
            """;
        
        Path systemPomPath = Paths.get(TARGET_BASE_PATH, 
            "interface-modules/interface-system/pom.xml");
        Files.createDirectories(systemPomPath.getParent());
        Files.writeString(systemPomPath, systemPom);
    }
    
    /**
     * 创建网关POM
     */
    private void createGatewayPom() throws IOException {
        String gatewayPom = """
            <?xml version="1.0" encoding="UTF-8"?>
            <project xmlns="http://maven.apache.org/POM/4.0.0"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                     http://maven.apache.org/xsd/maven-4.0.0.xsd">
                <modelVersion>4.0.0</modelVersion>
                <parent>
                    <groupId>com.yaoyi</groupId>
                    <artifactId>interface-platform</artifactId>
                    <version>1.0.0</version>
                </parent>
                
                <artifactId>interface-gateway</artifactId>
                
                <dependencies>
                    <dependency>
                        <groupId>org.springframework.cloud</groupId>
                        <artifactId>spring-cloud-starter-gateway</artifactId>
                    </dependency>
                    
                    <dependency>
                        <groupId>com.alibaba.cloud</groupId>
                        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
                    </dependency>
                </dependencies>
                
                <build>
                    <plugins>
                        <plugin>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-maven-plugin</artifactId>
                        </plugin>
                    </plugins>
                </build>
            </project>
            """;
        
        Path gatewayPomPath = Paths.get(TARGET_BASE_PATH, "interface-gateway/pom.xml");
        Files.createDirectories(gatewayPomPath.getParent());
        Files.writeString(gatewayPomPath, gatewayPom);
    }
    
    /**
     * 创建认证服务POM
     */
    private void createAuthPom() throws IOException {
        String authPom = """
            <?xml version="1.0" encoding="UTF-8"?>
            <project xmlns="http://maven.apache.org/POM/4.0.0"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                     http://maven.apache.org/xsd/maven-4.0.0.xsd">
                <modelVersion>4.0.0</modelVersion>
                <parent>
                    <groupId>com.yaoyi</groupId>
                    <artifactId>interface-platform</artifactId>
                    <version>1.0.0</version>
                </parent>
                
                <artifactId>interface-auth</artifactId>
                
                <dependencies>
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-web</artifactId>
                    </dependency>
                    
                    <dependency>
                        <groupId>com.yaoyi</groupId>
                        <artifactId>interface-common-security</artifactId>
                        <version>${project.version}</version>
                    </dependency>
                </dependencies>
                
                <build>
                    <plugins>
                        <plugin>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-maven-plugin</artifactId>
                        </plugin>
                    </plugins>
                </build>
            </project>
            """;
        
        Path authPomPath = Paths.get(TARGET_BASE_PATH, "interface-auth/pom.xml");
        Files.createDirectories(authPomPath.getParent());
        Files.writeString(authPomPath, authPom);
    }
    
    /**
     * 创建配置文件
     */
    private void createConfigFiles() throws IOException {
        System.out.println("\n>>> 创建配置文件...");
        
        // 创建业务模块配置文件
        createSystemModuleConfig();
        
        // 创建网关配置文件
        createGatewayConfig();
        
        // 创建认证服务配置文件
        createAuthConfig();
        
        System.out.println("  配置文件创建完成");
    }
    
    /**
     * 创建业务模块配置
     */
    private void createSystemModuleConfig() throws IOException {
        String config = """
            server:
              port: 9201
            
            spring:
              application:
                name: interface-system
              cloud:
                nacos:
                  discovery:
                    server-addr: localhost:8848
            """;
        
        Path configPath = Paths.get(TARGET_BASE_PATH, 
            "interface-modules/interface-system/src/main/resources/application.yml");
        Files.createDirectories(configPath.getParent());
        Files.writeString(configPath, config);
    }
    
    /**
     * 创建网关配置
     */
    private void createGatewayConfig() throws IOException {
        String config = """
            server:
              port: 9200
            
            spring:
              application:
                name: interface-gateway
              cloud:
                nacos:
                  discovery:
                    server-addr: localhost:8848
                gateway:
                  routes:
                    - id: interface-system
                      uri: lb://interface-system
                      predicates:
                        - Path=/system/**
            """;
        
        Path configPath = Paths.get(TARGET_BASE_PATH, 
            "interface-gateway/src/main/resources/application.yml");
        Files.createDirectories(configPath.getParent());
        Files.writeString(configPath, config);
    }
    
    /**
     * 创建认证服务配置
     */
    private void createAuthConfig() throws IOException {
        String config = """
            server:
              port: 9202
            
            spring:
              application:
                name: interface-auth
              cloud:
                nacos:
                  discovery:
                    server-addr: localhost:8848
            """;
        
        Path configPath = Paths.get(TARGET_BASE_PATH, 
            "interface-auth/src/main/resources/application.yml");
        Files.createDirectories(configPath.getParent());
        Files.writeString(configPath, config);
    }
    
    /**
     * 生成迁移报告
     */
    private void generateReport(Map<String, List<File>> classifiedFiles) throws IOException {
        System.out.println("\n>>> 生成迁移报告...");
        
        StringBuilder report = new StringBuilder();
        report.append("========================================\n");
        report.append("项目架构改造报告\n");
        report.append("========================================\n\n");
        report.append("源项目: ").append(SOURCE_PROJECT).append("\n");
        report.append("目标路径: ").append(TARGET_BASE_PATH).append("\n");
        report.append("改造时间: ").append(new Date()).append("\n\n");
        
        report.append("模块分布统计:\n");
        report.append("----------------------------------------\n");
        
        int totalFiles = 0;
        for (Map.Entry<String, List<File>> entry : classifiedFiles.entrySet()) {
            String module = entry.getKey();
            int fileCount = entry.getValue().size();
            totalFiles += fileCount;
            
            report.append(String.format("%-20s: %4d 个文件\n", module, fileCount));
        }
        
        report.append("----------------------------------------\n");
        report.append(String.format("总计: %d 个文件\n\n", totalFiles));
        
        report.append("模块说明:\n");
        report.append("----------------------------------------\n");
        report.append("1. API_SYSTEM: 对外API定义（DTO、Domain等）\n");
        report.append("2. COMMON_CORE: 公共核心模块（工具类、常量等）\n");
        report.append("3. COMMON_LOG: 日志模块\n");
        report.append("4. COMMON_MYBATIS: 数据库访问模块\n");
        report.append("5. COMMON_REDIS: Redis缓存模块\n");
        report.append("6. COMMON_SECURITY: 安全模块\n");
        report.append("7. COMMON_OSS: 对象存储模块\n");
        report.append("8. MODULES_SYSTEM: 业务模块（Controller、Service等）\n");
        report.append("9. GATEWAY: 网关\n");
        report.append("10. AUTH: 认证服务\n\n");
        
        report.append("后续工作:\n");
        report.append("----------------------------------------\n");
        report.append("1. 检查并修复包导入问题\n");
        report.append("2. 调整模块间的依赖关系\n");
        report.append("3. 完善各模块的配置文件\n");
        report.append("4. 编写启动类\n");
        report.append("5. 进行功能测试\n\n");
        
        // 输出到控制台
        System.out.println(report);
        
        // 保存到文件
        Path reportPath = Paths.get(TARGET_BASE_PATH, "REFACTOR_REPORT.txt");
        Files.writeString(reportPath, report.toString());
        
        System.out.println("  报告已保存到: " + reportPath);
    }
    
    /**
     * 主方法
     */
    public static void main(String[] args) {
        try {
            ProjectRefactorTool tool = new ProjectRefactorTool();
            tool.refactor();
        } catch (Exception e) {
            System.err.println("改造过程中出现错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

